#!/usr/bin/ruby
require "rubygems"
require "opengl"
require "glut"
require "m3g"
require "pp"

class MyGLUTWidget
  def initialize
    GLUT.Init
    GLUT.InitWindowSize 512, 512
    GLUT.InitDisplayMode GLUT::GLUT_DOUBLE | GLUT::GLUT_RGB | GLUT::GLUT_DEPTH
    GLUT.CreateWindow "Ruby-M3G"

    initialize_scene

    GLUT.ReshapeFunc  method(:reshape).to_proc()
    GLUT.DisplayFunc  method(:display).to_proc()
    GLUT.KeyboardFunc method(:keyboard).to_proc()
    GLUT.MouseFunc    method(:mouse).to_proc()
    GLUT.IdleFunc     method(:idle).to_proc()

  end

  def initialize_scene
    @wld = M3G::World.new
    cam = M3G::Camera.new
    cam.translate 0,0,10
    @wld.active_camera = cam
    @wld.add_child cam

    bg = M3G::Background.new
    bg.color = 0x000000ff
    @wld.background = bg;

    position_values = [1,-1,1,  1,1,1,  -1,-1,1,  -1,1,1,
                       -1,-1,-1,  -1,1,-1,  1,-1,-1,  1,1,-1,
                       -1,1,1,  -1,1,-1,  -1,-1,1,  -1,-1,-1]
    positions = M3G::VertexArray.new 12, 3, 2
    positions.set 0, 12, position_values
    scale = 1
    bias  = [0,0,0]

    texcoord_values =  [1,0, 1,1, 0,0, 0,1, 1,0, 1,1, 0,0, 0,1, 1,0, 0,0, 1,1, 0,1]
    texcoords = M3G::VertexArray.new 12, 2, 2
    texcoords.set 0, 12, texcoord_values
    texcoord_scale = 1
    texcoord_bias  = [0,0,0]

    vertices = M3G::VertexBuffer.new
    vertices.positions = positions, scale, bias
    vertices.tex_coords[0] = texcoords, texcoord_scale, texcoord_bias

    indices = [0,1,2,3, 2,3,4,5, 4,5,6,7, 6,7,0,1, 1,7,8,9, 0,10,6,11]
    strips  = [4,4,4,4,4,4]
    tris = M3G::TriangleStripArray.new indices, strips

    img, = M3G::Loader::load "kingyo.png"
    tex = M3G::Texture2D.new img

    app = M3G::Appearance.new
    app.texture[0] = tex

    @cube = M3G::Mesh.new vertices, tris, app
    @wld.add_child @cube

  end

  def reshape width, height
    g3d = M3G::Graphics3D::instance
    g3d.viewport = 0,0,width,height
    @wld.active_camera.perspective = 45, width/(height*1.0), 0.1, 1000
  end

  def display
    g3d = M3G::Graphics3D::instance
    g3d.render @wld
    GLUT.SwapBuffers()
  end
  
  def keyboard key, x, y
    if key == 113
      exit
    end
  end

  def mouse button, state, x, y
  end

  def idle
    @cube.post_rotate 1, 0,1,0
    GLUT.PostRedisplay
  end

  def start
    GLUT.MainLoop
  end

end


MyGLUTWidget.new.start

